package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.dto.DashboardStatsDTO;
import org.jeecg.modules.system.mapper.DashboardMapper;
import org.jeecg.modules.system.service.IDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 首页数据统计服务实现
 */
@Service
public class DashboardServiceImpl implements IDashboardService {

    @Autowired
    private DashboardMapper dashboardMapper;

    @Override
    public DashboardStatsDTO getDashboardStats() {
        DashboardStatsDTO stats = new DashboardStatsDTO();
        
        // 1. 获取今日新增订单
        Integer newOrders = dashboardMapper.selectTodayNewOrders();
        
        // 2. 获取待审订单
        Integer pendingReviewOrders = dashboardMapper.selectPendingReviewOrders();
        
        // 3. 获取总品类
        Integer inventorySum = dashboardMapper.selectInventorySum();
        
        // 4. 获取生产任务统计
        Map<String, Object> productionStats = dashboardMapper.selectProductionStats();
        Integer totalTasks = productionStats.get("total_tasks") != null ? 
            ((Number)productionStats.get("total_tasks")).intValue() : 0;
        Integer completedTasks = productionStats.get("completed_tasks") != null ? 
            ((Number)productionStats.get("completed_tasks")).intValue() : 0;
        Integer delayedTasks = productionStats.get("delayed_tasks") != null ? 
            ((Number)productionStats.get("delayed_tasks")).intValue() : 0;
        
        // 计算完成率
        double completionRate = totalTasks > 0 ? 
            BigDecimal.valueOf(completedTasks)
                    .divide(BigDecimal.valueOf(totalTasks), 4, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100))
                    .doubleValue() : 0;
                    
        // 计算延期率
        double delayedRate = totalTasks > 0 ?
            BigDecimal.valueOf(delayedTasks)
                    .divide(BigDecimal.valueOf(totalTasks), 4, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100))
                    .doubleValue() : 0;
        
        // 5. 获取库存分布
        List<Map<String, Object>> inventoryDistribution = dashboardMapper.selectInventoryDistribution();
        
        // 6. 获取最近警告
        List<Map<String, Object>> recentWarnings = dashboardMapper.selectRecentWarnings();
        
        // 设置统计数据
        stats.setTotalProduction(totalTasks);
        stats.setCompletedProduction(completedTasks);
        stats.setProcessingProduction(totalTasks - completedTasks - delayedTasks);
        stats.setDelayedProduction(delayedTasks);
        stats.setCompletionRate(completionRate);
        stats.setDelayedRate(delayedRate);
        
        // 设置库存预警数据
        stats.setTotalWarnings(inventorySum);
        // 统计各级别预警数量
        int highLevel = 0;
        int mediumLevel = 0;
        int lowLevel = 0;
        
        for (Map<String, Object> warning : recentWarnings) {
            Object level = warning.get("warning_level");
            if (level != null) {
                if (level.equals(1)) {
                    highLevel++;
                } else if (level.equals(2)) {
                    mediumLevel++;
                } else {
                    lowLevel++;
                }
            }
        }
        
        stats.setHighLevelWarnings(highLevel);
        stats.setMediumLevelWarnings(mediumLevel);
        stats.setLowLevelWarnings(lowLevel);
        
        // 设置任务统计数据
        stats.setPendingTasks(pendingReviewOrders);
        stats.setCompletedTasks(completedTasks);
        stats.setTaskCompletionRate(completionRate);
        
        // 转换警告数据格式
        List<Map<String, Object>> formattedWarnings = new ArrayList<>();
        for (Map<String, Object> warning : recentWarnings) {
            Map<String, Object> formattedWarning = new HashMap<>();
            String warningLevel = String.valueOf(warning.get("warning_level"));
            formattedWarning.put("id", warning.get("id"));
            formattedWarning.put("name", warning.get("material_name"));
            formattedWarning.put("desc", getWarningDescription(warningLevel));
            formattedWarning.put("current", warning.get("current_quantity"));
            formattedWarning.put("safe", warning.get("warning_quantity"));
            formattedWarning.put("level", getWarningLevel(warningLevel));
            formattedWarnings.add(formattedWarning);
        }
            
        stats.setRecentWarnings(formattedWarnings.toArray());
        
        return stats;
    }
    
    private String getWarningDescription(String warningLevel) {
        if (warningLevel == null) {
            return "库存预警";
        }
        switch (warningLevel) {
            case "1": return "库存严重不足";
            case "2": return "库存不足";
            case "3": return "库存正常";
            default: return "库存预警";
        }
    }
    
    private String getWarningLevel(String warningLevel) {
        if (warningLevel == null) {
            return "low";
        }
        switch (warningLevel) {
            case "1": return "high";
            case "2": return "medium";
            case "3": 
            default: return "low";
        }
    }
}
